<template>
  <bs-dialog :title="title" :visible.sync="editor" size="default" @closed="doCloseEdit" class="deviceDialog">
    <template slot="main">
      <el-tabs v-model="activeName" @tab-click="deviceTabsHandleClick">
        <el-tab-pane :label="$t('基本属性')" name="first">
        </el-tab-pane>
        <el-tab-pane :label="$t('播放属性')" name="second">
        </el-tab-pane>
        <el-tab-pane :label="$t('高级属性')" name="thread">
        </el-tab-pane>
        <el-tab-pane :label="$t('时间段')" name="four">
        </el-tab-pane>
        <!-- <el-tab-pane label="组播设置" name="five">
          <multicast-attr></multicast-attr>
        </el-tab-pane> -->
      </el-tabs>

      <el-form :inline="true" :model="editorForm" :rules="finalRules" ref="editorFormRef" label-width="110px" size="small" :show-message="false" :hide-required-asterisk="true" :status-icon="false">
        <input v-model="editorForm.id" type="hidden" />
        <div v-show="showArea.basicset">
          <basic-set :editor-form="editorForm"></basic-set>
        </div>
        <div v-show="showArea.palyattr">
          <play-attr :editor-form="editorForm"></play-attr>
        </div>
        <div v-show="showArea.advancedattr">
          <advanced-attr :editor-form.sync="editorForm"></advanced-attr>
        </div>
        <div v-show="showArea.timeslotdattr">
          <time-slot-attr :editor-form="editorForm"></time-slot-attr>
        </div>
      </el-form>
    </template>

    <template slot="footer">
      <bs-confirm-button-icon @click.native="doSave"></bs-confirm-button-icon>
      <bs-cancel-button-icon @click.native="doCloseEdit"></bs-cancel-button-icon>
    </template>
  </bs-dialog>
</template>

<script>
import BasicSet from "./BasicSet"
import PlayAttr from "./PlayAttr"
import AdvancedAttr from "./AdvancedAttr"
import TimeSlotAttr from "./TimeSlotAttr"
export default {
  name: 'EditDeviceDialog',
  data() {
    return {
      activeName: 'first',
      editor: false,
      editorForm: {},
      editorFormRules: {
        mac: [
            { required: true, message: '请输入MAC地址', trigger: 'blur' },
            { min: 12, message: 'MAC地址最小长度是12' },
            { pattern: /^[A-Za-z0-9]+$/, message: '只能为英文数字' }
        ],
        name: { required: true, message: '请输入终端名称', trigger: 'blur' },
        provinceId: { required: true, message: '请选择安装省', trigger: 'blur' },
        cityId: { required: true, message: '请选择安装城市', trigger: 'blur' },
        groupId: { required: true, message: '请选择终端分组', trigger: 'blur' },
        expiredDate: { required: true, message: '请选择到期日期', trigger: 'blur' },
        no: { pattern: /^[A-Za-z0-9]{10,10}$/, message: '编号只能为10位的英文数字组合' },
        osdPassword: { pattern: /^[0-9]{6,6}$/, message: 'OSD密码只能为6位数字' },
        telnetPassword: { pattern: /^[A-Za-z0-9]{6,6}$/, message: '系统密码只能为6位数字或字母' },
        heartbeatInterval: { pattern: /^(?!0)\d{1,3}$/, message: '心跳间隔时间只能为大于0的3位数字' },
        fileKeepDays: { pattern: /^[0-9]{0,2}$/, message: '自动清理文件天数只能为2位数字' },
        downloadSpeed: { pattern: /^(\d|[1-9]\d+)(\.\d+)?$/, message: '下载速度只能为大于等于0的数字' },
        apiServer: { pattern: /(http|https):\/\/([\w.]+\/?)\S*/, message: '请输入正确终端服务地址' },
        resServer: { pattern: /(http|https):\/\/([\w.]+\/?)\S*/, message: '请输入正确资源服务地址' },
      },
      batchEditorFormRules: {
        osdPassword: { pattern: /^[0-9]{6,6}$/, message: 'OSD密码只能为6位数字' },
        telnetPassword: { pattern: /^[A-Za-z0-9]{6,6}$/, message: '系统密码只能为6位数字或字母' },
        heartbeatInterval: { pattern: /^(?!0)\d{1,3}$/, message: '心跳间隔时间只能为大于0的3位数字' },
        fileKeepDays: { pattern: /^[0-9]{0,2}$/, message: '自动清理文件天数只能为2位数字' },
        downloadSpeed: { pattern: /^(\d|[1-9]\d+)(\.\d+)?$/, message: '下载速度只能为大于等于0的数字' },
        apiServer: { pattern: /(http|https):\/\/([\w.]+\/?)\S*/, message: '请输入正确终端服务地址' },
        resServer: { pattern: /(http|https):\/\/([\w.]+\/?)\S*/, message: '请输入正确资源服务地址' },
      },
      showArea: {
        basicset: true,
        palyattr: false,
        advancedattr: false,
        timeslotdattr: false,
        virtualscreenattr:false
      },
      title:  this.$t('新终端详细设置'),
      queryData: {}
    }
  },
  computed: {
    finalRules() {
      if (this.editorForm.macs || this.editorForm.updateGroupId){
        return this.batchEditorFormRules
      }else{
        return this.editorFormRules
      }
    }
  },
  created() {
    this.$eventBus.$on('addDeviceDialogShow', this.show);
  },
  beforeDestroy() {
    this.$eventBus.$off('addDeviceDialogShow');
  },
  components: {
    BasicSet,
    PlayAttr,
    AdvancedAttr,
    TimeSlotAttr,
  },
  methods: {
    resetForm() {
      this.editorForm = {
        // 基本属性
        mac: '',
        name: '',
        provinceId: '11',
        cityId: '1100',
        location: '',
        no: '',
        timeZone: 8,
        expiredDate: '',
        comment: '',
        onoffs: [],
        // 播放属性
        defaultBrightnessChecked : false,
        defaultVolumeChecked : false,
        defaultBrightness: 50,
        defaultVolume: 50,
        // 高级属性
        osdLanguage: 'zh',
        osdPassword: '',
        fileKeepDays: 7,
        telnetPassword: '',
        downloadSpeed: 0,
        heartbeatInterval: 30,
        logLevel: 'warn',
        // upgrade: false,
        resServer: '',
        // ftpServer: '',
        // ftpPort: '',
        // ftpUsername: '',
        // ftpPassword: '',
        downloads: [],
        tagIds:[],
        tagIdsString:[],
      }
      this.activeName = 'first'
    },
    // 显示
    show(form, queryData) {
      this.editorForm = form
      this.queryData = queryData
      if(form) {
        if(form.name) {
          this.title = `"${form.name}"`+this.$t('详细设置')
          this.$set(this.editorForm, 'defaultBrightnessChecked', true)
          this.$set(this.editorForm, 'defaultVolumeChecked', true)
        }
        if(form.macs || form.updateGroupId) {
          this.$set(this.editorForm, 'defaultBrightnessChecked', false)
          this.$set(this.editorForm, 'defaultVolumeChecked', false)
          // this.$set(this.editorForm, 'tagIds', [])
          this.$set(this.editorForm, 'tagIdsString', [])
          this.title = this.$t('多终端详细设置(仅设置需要修改的属性,为空则保持原值)')
        }
      }else{
        this.resetForm()
        this.title = this.$t('新终端详细设置')
        this.$set(this.editorForm, 'defaultBrightnessChecked', true)
        this.$set(this.editorForm, 'defaultVolumeChecked', true)
      }
      this.$nextTick(() => {
        this.$refs.editorFormRef.clearValidate();
        this.$eventBus.$emit('initBasicData');
      })
      this.editor = true
    },
    // 关闭
    doCloseEdit: function () {
      this.$refs.editorFormRef.clearValidate();
      this.$eventBus.$emit('closeDialog');
      this.resetForm()
      this.editor = false
      this.showArea = {
          basicset: true,
          palyattr: false,
          advancedattr: false,
          timeslotdattr: false,
        }
    },
    deviceTabsHandleClick(tab, event) {
      if(tab.name === 'first') {
        this.showArea = {
          basicset: true,
          palyattr: false,
          advancedattr: false,
          timeslotdattr: false,
        }
      }else if(tab.name === 'second') {
        this.showArea = {
          basicset: false,
          palyattr: true,
          advancedattr: false,
          timeslotdattr: false,
        }
      }else if(tab.name === 'thread') {
        this.showArea = {
          basicset: false,
          palyattr: false,
          advancedattr: true,
          timeslotdattr: false,
        }
      }else if(tab.name === 'four') {
        this.showArea = {
          basicset: false,
          palyattr: false,
          advancedattr: false,
          timeslotdattr: true,
        }
      }
    },
    // clearValidataByField(field) {
    //   this.$refs.editorFormRef.clearValidate(field);
    // },
    // 保存表单
    doSave() {
      if(this.editorForm.defaultBrightnessChecked != undefined && this.editorForm.defaultBrightnessChecked == false) {
        delete this.editorForm.defaultBrightness
      }
      if(this.editorForm.defaultVolumeChecked != undefined && this.editorForm.defaultVolumeChecked == false) {
        delete this.editorForm.defaultVolume
      }
      delete this.editorForm.defaultBrightnessChecked
      delete this.editorForm.defaultVolumeChecked
      delete this.editorForm.auditState
      console.log(this.editorForm)
      if(this.editorForm.macs || this.editorForm.updateGroupId) {
        if(this.editorForm.onoffs && this.editorForm.onoffs.length == 0){
          delete this.editorForm.onoffs
        }
        if(this.editorForm.downloads && this.editorForm.downloads.length == 0){
          delete this.editorForm.downloads
        }
        if(this.editorForm.tagIdsString && this.editorForm.tagIdsString.length == 0){
          delete this.editorForm.tagIds
          delete this.editorForm.tagIdsString
        }
        this.$refs.editorFormRef.validate(async valid => {
          if (valid) {
            this.$store.dispatch('device/doSetDeviceInfo', { ...this.editorForm, ...this.queryData }).then((res) => {
              if(res) {
                this.$message.success('修改成功')
                this.doCloseEdit()
                this.$eventBus.$emit('doList', { current: 1 })
              }
            })
          } else {
            let index = 0
            this.$refs.editorFormRef.fields.forEach(field => {
              if(field.validateMessage) {
                if(index === 0) {
                  console.log(field.validateMessage)
                  this.$message.error(field.validateMessage)
                  this.validateMsg=[]
                }
                index ++
              }
            })
            return
          }
        })
      }else{
        this.$refs.editorFormRef.validate(async valid => {
          if (valid) {
            const mac = (this.editorForm.mac).toUpperCase()
            const params = {
              ...this.editorForm,
              mac
            }
            if(this.editorForm.id){
              this.$store.dispatch('device/doUpdateDevice', params).then((res) => {
                if(res) {
                  this.$message.success('修改成功')
                  this.doCloseEdit()
                  this.$eventBus.$emit('doList', { current: 1 })
                }
              })
            }else{
              this.$store.dispatch('device/doAddDevice', params).then((res) => {
                if(res) {
                  this.$message.success('添加成功')
                  this.doCloseEdit()
                  this.$eventBus.$emit('doList', { current: 1 })
                }
              })
            }
          } else {
            let index = 0
            this.$refs.editorFormRef.fields.forEach(field => {
              if(field.validateMessage) {
                if(index === 0) {
                  console.log(field.validateMessage)
                  this.$message.error(field.validateMessage)
                  this.validateMsg=[]
                }
                index ++
              }
            })
            return
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__item {
  padding: 0 40px;
}
::v-deep .el-tabs__content {
  padding: 0px;
}
::v-deep .el-form {
  padding: 0 10px 0 15px;
}
::v-deep .el-dialog {
  width: 800px;
  height: 550px;
}
</style>
